﻿using B.S.AuthCenter.Api.Read.Application.Command.Approval;
using B.S.AuthCenter.Api.Read.DTOs.Approval;
using B.S.AuthCenter.Domain.Form;
using B.S.AuthCenter.ErrorCount;
using B.S.AuthCenter.InfrasIntructure.Interface;
using MediatR;
using Microsoft.IdentityModel.Tokens;

namespace B.S.AuthCenter.Api.Read.Application.Handler.Approval
{
    public class GetAppFormHandler : IRequestHandler<GetAppFormCommand, ApiPaging<ApprovalDTO>>
    {
        IBaseRepository<AppFormModel> appRepo;

        public GetAppFormHandler(IBaseRepository<AppFormModel> appRepo)
        {
            this.appRepo = appRepo;
        }

        public Task<ApiPaging<ApprovalDTO>> Handle(GetAppFormCommand request, CancellationToken cancellationToken)
        {
            ApiPaging<ApprovalDTO> res = new ApiPaging<ApprovalDTO>();
            var apps = appRepo.GetAll().Where(c => !c.IsDeleted);
            if (!string.IsNullOrEmpty(request.AppName))
            {
                apps = apps.Where(c => c.AppName.Contains(request.AppName));
            }
            if (request.Start != null && request.End != null)
            {
                apps = apps.Where(c => c.StartTime <= request.End && c.EndTime >= request.Start);
            }

            if (request.ApprovalState != null)
            {
                apps = apps.Where(c => c.ApprovalState == request.ApprovalState);
            }
            if(!string.IsNullOrEmpty(request.Name))
            {
                apps = apps.Where(x => x.AppName == request.Name || x.HeadName == request.Name);
            }
            
            var linq = from a in apps
                       select new ApprovalDTO
                       {
                           Id = a.Id,
                           AppName = a.AppName,
                           ApprovalState = a.ApprovalState,
                           ApprovalReason = a.ApprovalReason,
                           CreateTime = a.CreateTime,
                           Sorts = a.Sorts,
                           StartTime = a.StartTime,
                           DepartmentId = a.DepartmentId,
                           HeadName = a.HeadName,
                           EndTime = a.EndTime,
                           Reason = a.Reason,
                           ReportTime = a.ReportTime,
                           TotalTime = a.TotalTime,
                           State = a.State,
                       };
            res.TotalCount = linq.Count();
            res.TotalPage = (int)Math.Ceiling(res.TotalCount * 1.0/request.PageSize);
            res.Result=linq.OrderByDescending(c => c.Id).Skip((request.PageIndex-1)*request.PageSize).Take(request.PageSize).ToList();
            res.Msg = "查询申请列表成功";
            res.Code=ApiEnum.Success;
            return Task.FromResult(res);
        }
    }
}
